package netty.lora;

import io.netty.channel.Channel;
import netty.DataResponse;
import netty.util.ByteUtil;
import netty.util.ModBusUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author zhangtao
 * @create 2021/12/16 17:54
 */
public class SundaeRSTask implements Runnable {
    private static final Logger log = LoggerFactory.getLogger(SundaeRSTask.class);
    String stateData = "(12345678t0,0,0,0,${},11,12,13,00/05-00/05,1234,0,0,0,0&0x360x38\r";
    String countData = "(12345678p日期,右,中,左&0x360x38\r";
    Channel channel;
    ThreadLocalRandom random = ThreadLocalRandom.current();
    int count = 0;
    int make = 0;

    SundaeRSTask(Channel channel) {
        this.channel = channel;
    }

    @Override
    public void run() {
        try {
            DataResponse response = new DataResponse();
            byte[] bb = stateData.replace("${}", String.valueOf(random.nextInt(1, 20))).getBytes(StandardCharsets.UTF_8);
            int ri = ModBusUtils.alexCrc16(bb, bb.length - 2);
            bb[bb.length - 2] = (byte) (0xff & ri);
            bb[bb.length - 1] = (byte) ((0xff00 & ri) >> 8);
            response.setData(ByteUtil.bytes2HexStr(bb));
            response.setStationId("25963ffe");
            response.setLoraId("00066666");
            log.info(stateData);
            channel.writeAndFlush(response);
            count++;

            if (count == 10) {
                String d = countData.replace("日期", DateTime.now().toString("yyyy/MM/dd"))
                        .replace("左", String.valueOf(make++))
                        .replace("中", String.valueOf(make++))
                        .replace("右", String.valueOf(make++));
                bb = d.getBytes(StandardCharsets.UTF_8);
                ri = ModBusUtils.alexCrc16(bb, bb.length - 2);
                bb[bb.length - 2] = (byte) (0xff & ri);
                bb[bb.length - 1] = (byte) ((0xff00 & ri) >> 8);
                response.setData(ByteUtil.bytes2HexStr(bb));
                log.info(d);
                channel.writeAndFlush(response);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
